/*
 * Created by 岱青海蓝信息系统(北京)有限公司 on 17-6-9 上午10:18
 * Copyright (c) 2017. All rights reserved.
 */

package com.example.dqhl.recycleviewdemo.activity;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.SeekBar;
import android.widget.TextView;

import com.example.dqhl.recycleviewdemo.R;

/**
 * description: 播放视频Activity
 * autour:guanluocang
 * date:17/6/9 10:18
 */
public class SurfaceViewActivity extends AppCompatActivity implements View.OnClickListener {

    private SurfaceView surfaceView;
    private CheckBox button_play;
    private MediaPlayer mediaPlayer;
    private SeekBar seekBar;
    private int currentPosition;
    private boolean isPlaying;
    private TextView tv_time, tv_replay, tv_stop;

    String filepath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_surface_view);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//全屏不显示状态栏
        initView();
        initData();
        initListener();
        mediaPlayer = new MediaPlayer();
        surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//4.0一下的版本需要加该段代码。

        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                /**
                 * 当点击手机上home键（或其他使SurfaceView视图消失的键）时，调用该方法，获取到当前视频的播放值，currentPosition。
                 * 并停止播放。
                 */
                currentPosition = mediaPlayer.getCurrentPosition();
                stop();
            }

            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                /**
                 * 当重新回到该视频应当视图的时候，调用该方法，获取到currentPosition，并从该currentPosition开始继续播放。
                 */
                if (currentPosition > 0) {
                    play(currentPosition);
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format,
                                       int width, int height) {

            }
        });
    }


    public void initView() {
        (surfaceView) = (SurfaceView) findViewById(R.id.surfaceView);
        button_play = (CheckBox) findViewById(R.id.button_play);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        (tv_time) = (TextView) findViewById(R.id.tv_time);
        (tv_replay) = (TextView) findViewById(R.id.tv_replay);
        (tv_stop) = (TextView) findViewById(R.id.tv_stop);
    }

    public void initData() {
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int process = seekBar.getProgress();
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    mediaPlayer.seekTo(process);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {

            }
        });

    }

    private void initListener() {
        button_play.setOnClickListener(this);
        tv_replay.setOnClickListener(this);
        tv_stop.setOnClickListener(this);

        button_play.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    /**
                     * 播放
                     */
                    play(0);
                } else {
                    /**
                     * 暂停
                     */
                    pause();

                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_stop:
            /**
             * 停止
             */
                stop();
                break;

            case R.id.tv_replay:
            /**
             * 重播
             */
                replay();
                break;
        }
    }

    private void replay() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.seekTo(0);
        } else {
            play(0);
        }
    }

    private void stop() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.seekTo(0);
        }

    }

    private void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        } else {
            mediaPlayer.start();
        }

    }

    private void play(final int currentPosition) {
//        String path = filepath;//指定视频所在路径。
        String path = "http://2449.vod.myqcloud.com/2449_22ca37a6ea9011e5acaaf51d105342e3.f20.mp4";//指定视频所在路径。
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置视频流类型
        try {

            mediaPlayer.setDisplay(surfaceView.getHolder());
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepareAsync();
            Log.i("GG", mediaPlayer.getDuration() + "");
            tv_time.setText((mediaPlayer.getDuration() / 1000) + "s");

            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {

                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.start();
                    int max = mediaPlayer.getDuration();
                    seekBar.setMax(max);
                    mediaPlayer.seekTo(currentPosition);

                    new Thread() {

                        public void run() {
                            isPlaying = true;
                            while (isPlaying) {
                                int position = mediaPlayer.getCurrentPosition();
                                seekBar.setProgress(position);
                                try {
                                    Thread.sleep(500);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                            }

                        }

                        ;
                    }.start();
                }
            });

            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    button_play.setEnabled(true);
                }
            });

            mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    button_play.setEnabled(true);
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
